const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const TerserPlugin = require("terser-webpack-plugin");
const { merge } = require('webpack-merge') 
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
// 导入其他配置
const prodConfig = require('./webpack.prod')
const devConfig = require('./webpack.dev')

console.log();

const utils = require('./cdn.config')
// console.log(utils);
const externalConfig = JSON.parse(JSON.stringify(utils.externalConfig));  // 读取配置
const externalModules = utils.getExternalModules(externalConfig); // 获取到合适的路径（引用类型，自动改变）
// console.log(utils.getExternalModules(externalConfig));
console.log(externalConfig);

// base配置详细
// 定义对象保存 base 配置信息
const commonConfig = (isProduction) => {
  return  {
    // 入口
    entry: './src/main.js',
    // 出口
    output: {
      filename: '[name].[contenthash:8].build.js',
      path: path.resolve(__dirname, '../dist'),
      chunkFilename: 'js/chunk_[name].[contenthash:8].js'
      // publicPath: ''
    },
    externals: externalModules,
    // externals: {
    //   lodash: '_',
    //   vue: 'Vue'
    // },
    optimization: {
      // 当前文件的名称是按自然数进行编号排序，如果某个文件当前次不再被依赖那么重新打包时序号都会变
      chunkIds: 'deterministic',
      runtimeChunk: true,
      minimizer: [
        new TerserPlugin({
          extractComments: false,
        }),
      ],
      splitChunks: {
        chunks: 'all',
        cacheGroups: {
          vendors: {
            test: /[\\/]node_modules[\\/]/,       // 位置，找到node_modules
            filename: 'js/[contenthash:8].vendor.js',
            priority: -10,
          },
          default: {
            filename: 'js/[contenthash:8].syy_[id]_vendor.js',
            priority: -20,
            minChunks: 1,  // 模块被引用2次以上的才抽离
          }
        }
      }
    },
    resolve: {
      extensions: [".js", ".json", '.ts', '.jsx', '.vue'], 
      alias: {
        '@': path.resolve(__dirname, '../src')
      }
    },
    module: {
      rules: [
        {
          test: /\.css$/,
          use: [
            isProduction ? MiniCssExtractPlugin.loader : 'style-loader',
            {
              loader: 'css-loader',
              options: {
                importLoaders: 1
              }
            }, 
            // 'css-loader',
            'postcss-loader'
          ], 
        },
        {
          test: /\.less$/,
          use: [
            isProduction ? MiniCssExtractPlugin.loader : 'style-loader',
            {
              loader: 'css-loader',
              options: {
                importLoaders: 2
              }
            }, 
            // 'css-loader',
            'postcss-loader',
            "less-loader"
          ], 
        },
        {
          test: /\.(png|svg|gif|jpe?g)$/,
          type: 'asset',
          generator: {
            filename: "static/img/[name].[hash:7][ext]",
          },
        },
        {
          test: /\.(ttf|woff2?)$/,
          type: 'asset/resource',
          generator: {
            filename: "static/font/[name].[hash:7][ext]",
          },
        },
        {
          test: /\.(js|ts)$/,
          exclude: /node_modules/,    // 不对node_module下的js做处理
          use: ['babel-loader']
        },
        {
          test: /\.vue$/,
          use: ['vue-loader']
        },
        // {
        //   test: /\.ts$/,
        //   use: ['ts-loader']
        // }
      ]
    },
    plugins: [
      new HtmlWebpackPlugin({
        title: 'webpack5',
        template: './public/index.html',
        cdnConfig: externalConfig, // cdn配置
      }),
      
      new VueLoaderPlugin()
    ],
  }
}


module.exports = (env) => {
    // console.log(env.development);
    const isProduction = env.production 
    // 将环境变量添加到进程中
    process.env.NODE_ENV = isProduction ? 'production' : 'development'
    
    const config = isProduction ? prodConfig : devConfig

    const mergeConfig = merge(commonConfig(isProduction), config)
    return mergeConfig
}